package dao;

import java.util.LinkedList;

import bean.Class;
import bean.ClassActivityNews;
import bean.College;
import bean.News;
import db.RunSql;
import util.PathManager;

public class UserDao {
	private RunSql run;
	public UserDao() {
		this.run = new RunSql();
	}
	public boolean adminLogin(String name,String passwd) {
		String sql = "select * from admin where name='"+name+"' and passwd='"+passwd+"'";
		if(run.select(sql)!="") return true;
		else return false;
	}
	public boolean classLogin(String name,String college,String passwd) {
		String sql = "select * from class where name='"+name+"' and passwd='"+passwd+"' and college='"+college+"'";
		if(run.select(sql)!="") return true;
		else return false;
	}
	public boolean collegeLogin(String name,String passwd) {
		String sql = "select * from college where name='"+name+"' and passwd='"+passwd+"'";
		if(run.select(sql)!="") return true;
		else return false;
	}
	
	public boolean addClass(String college,String name,String passwd) {
		String sql = "insert into class(college,name,passwd) values('"+college+"','"+name+"','"+passwd+"');";
		if(run.update(sql)==1) return true;
		else return false;
	}
	public boolean addCollege(String name,String passwd) {
		String sql = "insert into college(name,passwd) values('"+name+"','"+passwd+"');";
		if(run.update(sql)==1) return true;
		else return false;
	}
	public LinkedList<College> getColleges() {
		String sql1 = "select * from college";
		String sql2 = "select * from class";
		String res1 = run.select(sql1);
		String res2 = run.select(sql2);
		return anData(res1,res2);
	}
	
	private LinkedList<College> anData(String collegeData,String classData) {
		LinkedList<College> list = new LinkedList<>();
		String[] coRow = collegeData.split("\u0006");
		for(String s:coRow) {
			String[] col = s.split("\u0005");
			if(col.length<=1) continue;
			College college = new College();
			college.setName(col[1]);
			college.setImgPath(PathManager.getCollegeRootPathByName(col[1])+"/"+col[1]+".jpg");
			list.add(college);
		}
		String[] clRow = classData.split("\u0006");
		for(String s:clRow) {
			String[] col = s.split("\u0005");
			if(col.length<=1) continue;
			Class c = new Class();
			c.setCollege(col[1]);
			c.setName(col[2]);
			c.setImg(PathManager.getClassRootPathByName(col[1], col[2])+"/"+col[2]+".jpg");
			for(College a:list)
				if(a.getName().equals(col[1])) a.addClass(c);
			
		}
		return list;
	}

}
